/*********************************************************************************
 *      Copyright:  (C) 2020 makun<1394987689@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  thread.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(2020年03月02日)
 *         Author:  makun <1394987689@qq.com>
 *      ChangeLog:  1, Release initial version on "2020年03月02日 10时18分27秒"
 *                 
 ********************************************************************************/
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
void *thread_worker1(void *args);
void *thread_worker2(void *args);

int main (int argc, char **argv)
{
    int shared_var = 1000;
    pthread_t    tid;//定义一个线程
    pthread_attr_t  thread_attr;//定义线程属性

if(pthread_attr_init(&thread_attr))//初始化线程
{
    printf("pthread_attr_init()failure:%s\n",strerror(errno));
    return -1;
}
if(pthread_attr_setstacksize(&thread_attr,120*1024))//设置线程属性栈的大小
{
    printf("pthread_attr_setstacksize()failure:%s\n",strerror(errno));
    return -2;
}
if(pthread_attr_setdetachstate(&thread_attr,PTHREAD_CREATE_DETACHED))//设置线程为可分离状态
{
    printf("pthread_attr_setdetachstate()failure:%s\n",strerror(errno));
    return -3;
}
pthread_create(&tid,&thread_attr,thread_worker1,&shared_var);//&tid,用来返回该线程的id，第二个参数是线程的属性，第三个参数是子线程要完成的任务，第四个参数是传给所调用的函数的指针
printf("Thread worker1 tid[%ld]created ok\n",tid);

pthread_create(&tid,NULL,thread_worker2,&shared_var);
printf("Thread worker2 tid[%ld]created ok\n",tid);

pthread_attr_destroy(&thread_attr);//用完以后要摧毁

pthread_join(tid,NULL);//线程2需要主线程调用pthread_join等待它退出

while(1)
{
    printf("main thread shared_var:%d\n",shared_var);
    sleep(10);
}
}
void *thread_worker1(void *args)
{
    int  *ptr = (int *)args;
    if( !args )
    {
        printf("%s()get invalid arguments\n", __FUNCTION__);
        pthread_exit(NULL);
    }
    printf("Thread worker1 [%ld]start running..\n",pthread_self());//打印自己的线程id
    while(1)
    {
        printf("+++ %s before shared_var++:%d\n", __FUNCTION__,*ptr);
        *ptr+=1;//*ptr=*ptr+1
        sleep(2);
        printf("+++:%s after sleep shared_var:%d\n", __FUNCTION__,*ptr);
    }
    printf("Thread worker 1 exit...\n");

    return NULL;
}
void *thread_worker2(void *args)
{
    int    *ptr = (int *)args;
    printf("%s()get invalid arguments\n", __FUNCTION__);
    pthread_exit(NULL);

    printf("Thread worker2 [%ld]start running..\n",pthread_self());

    while(1)
    {
        printf("--- %s before shared_var++:%d\n", __FUNCTION__,*ptr);
        *ptr+=1;//* ptr=*ptr+1 
        sleep(2);
        printf("---:%s after sleep shared_var:%d\n", __FUNCTION__,*ptr);
    }
    printf("Thread worker 2 exit...\n");
    return NULL;
}



